const webSocketServer = require("ws").Server;
const wss = new webSocketServer({ port: 3000 });
const GameCtr = require("./gameCtr");

wss.on("connection", (ws) => {
    console.log(ws._socket.remoteAddress.split("::ffff:")[1]);
    ws.onmessage = function (msg) {
        let pak = JSON.parse(msg.data);
        // 获取请求类型
        let type = pak.type;
        // 获取传来的数据
        let data = pak.data;
        if (type === GameCtr.Protocol.REGISTER) {
            // 如果接收到的是注册请求
            pak["data"] = register_request(data);
        } else if (type === GameCtr.Protocol.LOGIN) {
            pak["data"] = login_request(data);
            GameCtr.playerManager.creatPlayer(pak["data"], ws, GameCtr);
        } 
        ws.send(JSON.stringify(pak));
    };
});

// 处理登录请求
function login_request(data) {
    let { accountID, password } = data;
    // 根据account找到用户信息
    let userInfo = GameCtr.OPT.findUser(accountID);
    if (userInfo && String(userInfo.password) === String(password)) {
        let packet = {};
        packet.accountID = userInfo.accountID;
        packet.gold = userInfo.gold;
        // packet.avatarUrl = userInfo.avatarUrl;
        return { err: null, info: packet };
    } else {
        return { err: "账号或密码错误" };
    }
}

// 处理注册请求
function register_request(data) {
    let packet = GameCtr.OPT.findUser(data.accountID);
    if (packet) {
        return { err: "注册失败，账号已被使用！" };
    } else {
        // 将账号密码加入表格
        GameCtr.OPT.addUser(data);
        return { err: null, info: { accountID: data.accountID } };
    }
}
